package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.base.response.JsonResult;
import cn.tedu._05weibo.base.response.StatusCode;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.bto.UserLoginDTO;
import cn.tedu._05weibo.pojo.bto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    // 用户注册功能
    @ApiOperation(value = "注册功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO){
        // 日志方式打印
        log.debug("userRegDTO = {}", userRegDTO);
        // 接收用户名
        String username=userRegDTO.getUsername();
        // 判断用户名是否存在
        UserVO userVO = userMapper.selectByUsername(username);
        log.debug("userVO = " + userVO);
        if (userVO != null){
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }
        // 插入数据
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return JsonResult.ok();
    }

    // 用户登录功能
    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session){
        String username = userLoginDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);
        // 判断用户名是否存在
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        // 判断密码内容是否相同
        if (userVO.getPassword().equals(userLoginDTO.getPassword())){
            //保存该用户的session会话到服务器内存中
            session.setAttribute("user",userVO);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.PASSWORD_ERROR);
    }

    // 获取当前用户功能，校验用户的登录状态
    @ApiOperation(value = "获取当前用户功能")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        // 在服务器内存中，获取会话状态
        UserVO userVO= (UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }

    // 退出用户登录功能
    @ApiOperation(value = "退出登录功能")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session){
        // 删除会话标识
        session.removeAttribute("user");
    }


}
